<template>
    <div class="box">
        <header>
            <span>
                在线调试
                <el-button @click="handleOpenEnv">管理环境变量</el-button>
            </span>
            <!-- <img src="@/assets/GETlogo1.png" alt="logo" srcset="" height="32px" @click="view"> -->
        </header>
        <Split v-model="split" mode="vertical">
            <template #top>
                <div class="top-panel">
                    <QueryForm :data="tabData.info" @debug="handleDebug" @form-value="handleFormValue" />
                    <QueryCom :isenable="false" :editor="true" :data="tabData.info"
                        @query-com-value="handleQueryComValue" />
                </div>
            </template>
            <template #bottom>
                <div class="bottom-panel">
                    <ResponseCom :data="tabData.response" />
                </div>
            </template>
        </Split>
        <environmentDialog ref="environmentDialogRef" />
    </div>
</template>

<script setup lang="ts">
import QueryForm from '@/components/QueryForm.vue'
import QueryCom from '@/components/QueryCom.vue'
import ResponseCom from '@/components/ResponseCom.vue'
import { ref, onMounted } from 'vue'
import { apiDebug } from '@/api'
import { isValidDateTime } from '@/utils/dateUtil'
import environmentDialog from '@/components/dialog/environmentDialog.vue'
import { formatSwaggerToRequests1 } from '@/utils/url'
import service from '@/utils/request'
const emit = defineEmits(['save-case', 'debug', 'queryComValue', 'save', 'delete-node', 'open-env'])
const environmentDialogRef = ref()
const split = ref(0.5)
const apiList = ref([] as any)
const tabData = ref({
    info: {
        requestType: '',
        url: '',
        params: [],
        body: "",
        bodyForm: [],
        headers: [],
        cookies: [],
        auth: "",
        requestContentType: ""
    },
    response: {}
})
/** 向上传递参数变量 */
let queryValue = {} as any

const view = () => {
    window.open('https://itest.geovisearth.com/')
}

const init = async () => {
    try {
        const url = location.search.split("?url=")[1]
        const result = await service.get(decodeURIComponent(url))
        apiList.value = formatSwaggerToRequests1(result.data)
        const apiObj = apiList.value[0]
        tabData.value.info = {
            requestType: apiObj.method,
            url: apiObj.urls[0],
            params: apiObj.parameters.queryParams ? apiObj.parameters.queryParams.map(item => {
                return {
                    keyName: item.name,
                    keyValue: item.example || '',
                    keyType: item.type || 'string',
                    keyDesc: item.description
                }
            }) : [],
            body: JSON.stringify(apiObj.parameters.body),
            bodyForm: apiObj.parameters.urlencoded ? apiObj.parameters.urlencoded.map(item => {
                return {
                    keyName: item.name,
                    keyValue: item.example || '',
                    keyType: item.type || 'string',
                    keyDesc: item.description
                }
            }) : [],
            headers: apiObj.parameters.headers ? apiObj.parameters.headers.map(item => {
                return {
                    keyName: item.name,
                    keyValue: item.example || '',
                    keyType: item.type || 'string',
                    keyDesc: item.description
                }
            }) : [],
            cookies: [],
            auth: "",
            requestContentType: apiObj.parameters.body ? 'json' : (apiObj.parameters.formData ? 'x-www-form-urlencoded' : 'none')
        }
        console.log('解析后的参数' + apiList)
    } catch (error) {
        console.log(error)
    }
}

const handleDebug = async () => {
    try {
        // params 处理
        let paramsValue = []
        if (
            ['form-data', 'x-www-form-urlencoded'].includes(queryValue.requestContentType) &&
            queryValue.bodyForm?.length
        ) {
            paramsValue = queryValue.bodyForm || []
            paramsValue.forEach((item: any) => {
                if (isValidDateTime(item.keyValue)) {
                    item.keyValue = encodeURI(item.keyValue)
                }
            })
        } else {
            paramsValue = queryValue.params || []
            paramsValue.forEach((item: any) => {
                if (isValidDateTime(item.keyValue)) {
                    item.keyValue = encodeURI(item.keyValue)
                }
            })
        }
        // headers处理 1.存在auth,Headers中有Authorization时进行替换，没有时进行添加2.不存在auth时，直接使用Headers
        let headers = [] as any
        if (queryValue.auth) {
            if (!queryValue.headers?.length) {
                headers = [
                    {
                        keyName: 'Authorization',
                        keyValue: queryValue.auth,
                        keyType: 'string'
                    }
                ]
            } else {
                const isHasAuthorization = queryValue.headers.some((q: any) => q.keyName == 'Authorization')
                if (isHasAuthorization) {
                    headers = queryValue.headers.map((item: any) => {
                        if (item.keyName == 'Authorization') {
                            return {
                                ...item,
                                keyValue: queryValue.auth,
                                keyType: 'string'
                            }
                        }
                        return item
                    })
                } else {
                    headers = [
                        ...(queryValue.headers || []),
                        {
                            keyName: 'Authorization',
                            keyValue: queryValue.auth,
                            keyType: 'string'
                        }
                    ]
                }
            }
        } else {
            headers = [...(queryValue.headers || [])]
        }
        const apiParams = {
            protocal: queryValue.query.protocal,
            requestType: queryValue.query.requestType,
            url: queryValue.query.url,
            requestContentType: queryValue.requestContentType || '',
            requestHeaderList: headers,
            requestParamsList: paramsValue,
            requestBodyList: [],
            requestBody: queryValue.body || '',
            envVarsList: JSON.parse(localStorage.getItem('environmentParams') || '[]')
        }
        const { data } = await apiDebug(apiParams)
        let {
            responseHeaders,
            responseContent,
            requestBody,
            requestHeaderList,
            requestParamsList,
            responseResult,
            responseCode,
            responseTime,
            responseSize,
            requestUrl,
            cookies,
            responseContentType,
            extractorResponse,
            assertInfos,
            imageUrl
        } = data
        tabData.value.response = {
            requestHeaderList,
            requestBody,
            requestParamsList,
            responseHeaders,
            responseContent,
            extractorResponse,
            assertInfos,
            imageUrl,
            responseResult: {
                responseCode,
                responseTime,
                responseSize,
                responseResult,
                requestUrl,
                cookies,
                responseContentType
            }
        }
    } catch (error) {
        tabData.value.response = {
            requestHeaderList: [],
            requestBody: '',
            requestParamsList: [],
            responseHeaders: [],
            responseContent: '',
            extractorResponse: [],
            assertInfos: [],
            imageUrl: '',
            responseResult: {
                responseCode: '',
                responseTime: '',
                responseSize: '',
                responseResult: '',
                requestUrl: '',
                cookies: [],
                responseContentType: ''
            }
        }
    }

}

/** 向上传递form、请求参数变量 */
const handleFormValue = (value: any) => {
    queryValue = {
        ...queryValue,
        query: value
    }
}
/** 向上传递form、请求参数变量 */
const handleQueryComValue = (value: any) => {
    queryValue = {
        ...queryValue,
        ...value
    }
}

const handleOpenEnv = () => {
    environmentDialogRef.value.open()
}

onMounted(() => {
    init()
})
</script>

<style scoped>
.box {
    width: 100%;
    height: 100%;
}

.ivu-split-wrapper {
    height: calc(100% - 72px);
}

.top-panel,
.bottom-panel {
    padding: 16px;
    height: 100%;
    overflow: auto;
}

/* 可选：自定义分割线样式 */
:deep(.ivu-split-trigger-vertical) {
    height: 4px;
    background: #e8e8e8;
}

:deep(.ivu-split-trigger-vertical:hover) {
    background: #d6d6d6;
}

header {
    color: #333;
    padding: 20px 10px;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-button {
        margin-left: 10px;
    }

    img {
        cursor: pointer;
    }
}

:deep(.memorize_new_word) {
    text-decoration-color: transparent;
}

:deep(.el-tabs) {
    height: 100%;

    .el-tab-pane {
        height: 100%;
    }
}


.response {
    position: relative;
    width: 100%;
    height: 100%;

    .result {
        position: absolute;
        top: 0;
        right: 10px;
        display: flex;
        width: 200px;
        height: 40px;
        font-size: 12px;
        justify-content: space-between;
        align-items: center;

        &-text {
            display: inline-block;
            padding: 2px 5px;
            border-radius: 4px;
        }
    }

    .el-tabs {
        height: 100%;
    }
}

:deep(.multiple-edit-dialog) {
    height: 530px;

    .el-dialog__body {
        /* height: calc(100% - 150px); */
    }
}
</style>
